<?php

namespace common\models\business;

use Yii;
use yii\db\Exception;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\business\BusinessContractPurchase;


/**
 * This is the model class for table "business_contract".
 *
 * @property string $id
 * @property integer $cateid
 * @property string $name
 * @property string $no
 * @property string $partyA
 * @property string $partyB
 * @property string $amount
 * @property string $advance_ratio
 * @property integer $start_time
 * @property integer $end_time
 * @property string $final_amount
 * @property integer $final_num
 * @property string $address
 * @property string $afile
 * @property string $aopenbank
 * @property string $aopenbankadd
 * @property string $aopenbankaccount
 */
class BusinessContract extends \yii\db\ActiveRecord
{




    const STATUS_NOMAL = 0;
    const STATUS_OUT = 1;
    const STATUS_WILLOUT = 2;
    public static $statues = [
        self::STATUS_NOMAL => '生效中',
        self::STATUS_OUT => '已过期',
        self::STATUS_WILLOUT => '即将过期',
    ];

    //主要用于日志记录
    public $uselog = [
        'tabcomment' => '合同',      //用于修改了什么的显示
        'mainfield' => 'name',      //主要的显示标题的字段
        'picturefield' => ['afile'],        //图片字段
        'timefield' => ['start_time','end_time'],       //时间字段
        'unsetfiled' =>[],      //不需要记录的字段
    ];

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'business_contract';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cateid', 'name', 'no', 'partyA', 'partyB', 'start_time', 'end_time'], 'required'],
            [['cateid', 'final_num','displayorder','num'], 'integer'],
            [['final_amount','final_num'],'number'],
            [['amount', 'advance_ratio'], 'number'],
            [['name', 'no', 'partyA', 'partyB', 'address', 'aopenbank', 'aopenbankadd', 'aopenbankaccount'], 'string', 'max' => 255],
            [['afile'], 'image','extensions' => 'jpg, jpeg, gif, png','minWidth' => 600,'maxWidth' => 1200,'minHeight' =>500,'maxHeight' => 2500,'on'=>'create,update'],
            [['start_time', 'end_time'],'safe'],
            [['no'],'unique'],


            [['final_amount','final_num'],'filter', 'filter'=>'floatval'],
            ['final_num','filter','filter'=>'intval'],
        ];
    }



    public function scenarios()
    {
        $scenarios = parent::scenarios();//本行必填，不写的话就会报如上错误
        $scenarios['create'] = ['afile'];
        $scenarios['update'] = ['afile'];

        return $scenarios;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cateid' => '分类',
            'name' => '合同名称',
            'no' => '合同编号',
            'partyA' => '甲方',
            'partyB' => '乙方',
            'amount' => '签订的金额',
            'num' => '签订的数量',
            'advance_ratio' => '预付比例',
            'start_time' => '生效时间',
            'end_time' => '失效时间',
            'final_amount' => '决算金额',
            'final_num' => '决算数量',
            'address' => '签单地址',
            'afile' => '合同内容',
            'aopenbank' => '甲方开户行',
            'displayorder' => '显示顺序',
            'aopenbankadd' => '甲方开户行地址',
            'aopenbankaccount' => '甲方开户行账户',
        ];

    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取结算单
     */
    public function getStatements()
    {
        return $this->hasMany(BusinessContractStatements::className(),['contract_id'=>'id']);
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取购进单
     */
    public function getPurchase()
    {
        return $this->hasMany(BusinessContractPurchase::className(),['contract_id'=>'id']);
    }

    /**
     * @param $contractid
     * @param $fieldid
     * @return mixed
     * 获取附加字段的值
     */
    public static function fieldValue($contractid,$fieldid)
    {
        $value = BusinessContractFieldvalue::find()->select('value')->where('contractid=:id and fieldid=:fid',[':id'=>$contractid,':fid'=>$fieldid])->asArray()->one();
        return $value['value'];
    }


    /**
     * @return array|\yii\db\ActiveRecord[]
     * 取出所有的分类
     */
    public static function Allcate()
    {
        return BusinessContractCategory::find()->asArray()->all();
    }


    public function beforeSave($insert)
    {
        $this->start_time = strtotime($this->start_time);
        $this->end_time = strtotime($this->end_time);
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }




    /**
     * 判断选择的字段是否显示
     */
    public static function isShow($field,$hidden_fileds)
    {
        if(in_array($field,$hidden_fileds)){
            return true;
        }
        return false;
    }


    /**
     * @param $contarct_id
     * @return array
     * 获取合同下的所有购进单
     */
    public static function allPurchase($contarct_id)
    {
        return (new Query())
            ->select('id,name')
            ->from(BusinessContractPurchase::tableName())
            ->where('contract_id=:id',[':id'=>$contarct_id])
            ->all();
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取合同所属分类
     */
    public function getCategory()
    {
        return $this->hasOne(BusinessContractCategory::className(),['id'=>'cateid']);
    }


    /**
     * @return mixed
     * 获取合同的附加字段
     */
    public function getAddonField()
    {
        return $this->category->hasMany(BusinessContractField::className(),['cateid'=>'id']);
    }


    /**
     * @return $this
     * 已经购进的购进单的金额
     */
    public function getPurchasePrice()
    {
        $sumprice = new Expression('sum(price) as sumprice');
        $total = BusinessContractPurchase::find()
            ->select($sumprice)
            ->where('contract_id=:id status=:status',[':id'=>$this->id,':status'=>BusinessContractPurchase::STATUS_AGREE])
            ->scalar();

        return $total?$total:0;
    }


    /**
     * @return $this
     * 已经购进的购进单的数量
     */
    public function getPurchaseNum()
    {
        $sumnum = new Expression('sum(num) as sumnum');
        $total = BusinessContractPurchase::find()
            ->select($sumnum)
            ->where('contract_id=:id and status=:status',[':id'=>$this->id,':status'=>BusinessContractPurchase::STATUS_AGREE])
            ->scalar();
        return $total?$total:0;
    }


    /**
     * @return false|null|string
     * 获取已经结算的金额
     */
    public function getFinishPrice(){
        $sumprcie = new Expression('sum(price) as sumfprice');
        $total = BusinessContractStatements::find()
            ->select($sumprcie)
            ->where('contract_id=:id and status=:status',[':id'=>$this->id,':status'=>BusinessContractPurchase::STATUS_AGREE])
            ->scalar();
        return $total?$total:0;
    }


    /**
     * @return false|null|string
     * 获取已经结算的数量
     */
    public function getFinishNum(){
        $sumnum = new Expression('sum(num) as sumfnum');
        $total = BusinessContractStatements::find()
            ->select($sumnum)
            ->where('contract_id=:id and status=:status',[':id'=>$this->id,':status'=>BusinessContractPurchase::STATUS_AGREE])
            ->scalar();
        return $total?$total:0;
    }









}
